package com.iflytek.crvoice2txt.util;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.util.Log;

public class AudioUtil {

    private final static String TAG = "AudioUtil";

    private MediaPlayer mMediaPlayer;

    private AudioEvent audioEvent;

    public void setAudioEvent(AudioEvent audioEvent) {
        this.audioEvent = audioEvent;
    }

    public interface AudioEvent {
        void onAudioPlayEnd(MediaPlayer mp);
    }

    public AudioUtil() {
        this.mMediaPlayer = new MediaPlayer();
    }

    public void startPlay(String path) {
        if (path == null) {
            Log.i(TAG, "播放音频路径为空");
            return;
        }
        try {
            if (mMediaPlayer != null) {
                mMediaPlayer.reset();
            }else {
                mMediaPlayer = new MediaPlayer();
            }
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (audioEvent != null) {
                        audioEvent.onAudioPlayEnd(mp);
                    }
                }
            });
            mMediaPlayer.prepare();
            if (!mMediaPlayer.isPlaying()) {
                mMediaPlayer.start();
            }
        } catch (Exception e) {
            Log.i(TAG, "MediaPlayer播放失败！");
        }
    }

    public void stopPlay() {
        if (mMediaPlayer != null) {
            mMediaPlayer.stop();
        }
    }

    public void release() {
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
}
